import axios from "axios";
import { message as Message } from 'ant-design-vue'
import errorCode from "@/utils/error-code";
import { BASE_URL } from "./config";

// 默认配置
const defaultConfig = {
  baseURL: BASE_URL,
  timeout: 10000,
};

// 创建 axios 实例
const createAxiosInstance = (config = {}) => {
  const instance = axios.create({
    ...defaultConfig,
    ...config,
  });

  return instance;
};

// 错误信息处理
const handleError = (message) => {
  if (message === "Network Error") {
    return "Backend interface connection abnormality";
  } else if (message.includes("timeout")) {
    return "System interface request timeout";
  } else if (message.includes("Request failed, status code error")) {
    return (
      "System Interface " + message.substr(message.length - 3) + " abnormal"
    );
  }
  return message;
};

// 统一的错误处理
const errorHandler = (error) => {
  // 记录错误日志
  console.error("Request error:", error);
  const message = handleError(error.message);
  Message.error(message);
  return Promise.reject(error);
};

// 请求拦截器
const requestInterceptor = (config) => {
  const authorization = sessionStorage.getItem("authorization");

  if (authorization) {
    config.headers.Authorization = `Basic ${authorization}`;
  }

  return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
  const { responseType } = response.request;
  const { code, errorCode: responseErrorCode, msg } = response.data;
  const message =
    errorCode[responseErrorCode] || msg || errorCode["default"];

  // 处理文件下载类响应
  if (["blob", "arraybuffer"].includes(responseType)) {
    return response.data;
  }

  // 错误状态处理 (包含code为500的情况)
  if (code === 500 || code !== 0) {
    Message.error(message);
    return Promise.reject(new Error(message));
  }

  return response.data;
};

// Axios 工厂函数
const createRequest = (config) => {
  const instance = createAxiosInstance(config);

  // 添加请求拦截器
  instance.interceptors.request.use(requestInterceptor, errorHandler);

  // 添加响应拦截器
  instance.interceptors.response.use(responseInterceptor, errorHandler);

  return instance;
};

// 封装请求模块
const request = {
  get: (url, params, config = {}) => {
    const instance = createRequest(config);
    return instance.get(url, { params });
  },

  post: (url, data, config = {}) => {
    const instance = createRequest(config);
    return instance.post(url, data);
  },

  put: (url, data, config = {}) => {
    const instance = createRequest(config);
    return instance.put(url, data);
  },

  delete: (url, data, config = {}) => {
    const instance = createRequest(config);
    return instance.delete(url, { data });
  },

  // 支持多实例创建
  createInstance: (config) => {
    return createRequest(config);
  },

  // 支持请求取消
  cancelRequest: (cancelToken) => {
    const instance = createRequest();
    return instance.cancelToken(cancelToken);
  },
};

export default request;
